package sample.Stage2;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.stage.Window;
import sample.Main;
import sample.ProgressStage;
import sample.SendRouterOrder.Order_AutoControl;
import sample.SendRouterOrder.Router;
import sample.SendRouterOrder.SendRouter;
import sample.tools.*;

import java.net.URL;
import java.util.Arrays;
import java.util.ResourceBundle;

/**
 * 作者：w on 2021-08-20.
 * 邮箱：y141111@126.com
 * 版本：v1.0
 */
public class SettingRouterController extends Window implements Initializable{
    @FXML
    public WebView stage2_webView;
    public Button stage2_back;
    public ChoiceBox<String> stage2_choiceBox;
    public Button stage2_confirm;

    public int currentSelectRouter;
    public Label stage2_1;  // 位置
    public Label stage2_2;  // 总行程
    public Label stage2_3;  // 工作距离
    public Label stage2_4;  // 能源消耗
    public Label stage2_5;  // 行驶次数
    public Label stage2_6;  // 障碍物
    public Label stage2_7;  // 路况
    public Label stage2_8;  // 实时天气
    public Label stage2_9;  // 实时天气信息

    private Stage getStage(){
        return (Stage) stage2_webView.getScene().getWindow();
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        final WebEngine webengine = stage2_webView.getEngine();
        String url = Main.class.getResource("/sample/html/index.html").toExternalForm();
        webengine.load(url);
        stage2_choiceBox.getItems().add(0,"路线一");
        stage2_choiceBox.getItems().add(1,"路线二");
        stage2_choiceBox.getItems().add(2,"路线三");
        stage2_choiceBox.getItems().add(3,"路线四");
//        stage2_choiceBox.getSelectionModel().select(0);//默认选第一个
        stage2_choiceBox.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>() {
            public void changed(ObservableValue ov,
                                Number value, Number new_value) {
                JavaUseJS.Run(stage2_webView, "clearAllInfo()");
                currentSelectRouter = (int) new_value;
                String[][] router = Router.router1;
                switch (currentSelectRouter){
                    case 0:
                        router = Router.router1;
                        break;
                    case 1:
                        router = Router.router2;
                        break;
                    case 2:
                        router = Router.router3;
                        break;
                    case 3:
                        router = Router.router4;
                        break;
                }
                stage2_1.setText((int) new_value == 0 ? "位置：图书馆" : (int)new_value == 1 ? "位置：操场" : "位置：校园");  // 位置
                stage2_2.setText((int) new_value == 0 ? "总行程：600米" : (int)new_value == 1 ? "总行程：900米" : "总行程：1300米");  // 总行程
                stage2_3.setText((int) new_value == 0 ? "工作距离：100米" : (int)new_value == 1 ? "工作距离：900米" : "工作距离：900米");  // 工作距离
                stage2_4.setText((int) new_value == 0 ? "能源效率：" : (int)new_value == 1 ? "能源效率：" : "能源效率：");  // 能源消耗
                stage2_5.setText((int) new_value == 0 ? "行驶次数：63次" : (int)new_value == 1 ? "行驶次数：52次" : "行驶次数：58次");  // 行驶次数
                stage2_6.setText((int) new_value == 0 ? "障碍物：0" : (int)new_value == 1 ? "障碍物：1" : "障碍物：2");  // 障碍物
                stage2_7.setText((int) new_value == 0 ? "路况:水泥路" : (int)new_value == 1 ? "路况:水泥路" : "路况:水泥路");  // 路况
                stage2_8.setText((int) new_value == 0 ? "实时天气" : (int)new_value == 1 ? "实时天气" : "实时天气");  // 实时天气
//                String str = WeatherUtil.getLuoYangTianQi();
                new Thread(()->{
                    try {
                        String[] weather = WeatherUtilsBaiDuSearch.getWeather("瀍河");
                        StringBuilder str = new StringBuilder();
                        String[] wDate = weather[0].split(" ");
                        for (String a: wDate){
                            str.append(a).append("\n");
                        }
                        str.append("\n");
                        for (int i = 1; i < weather.length; i ++){
                            str.append(i == 1? "空气质量：": i == 2? "当前温度：": i == 3? "今日风级：" : i == 4? "天气状况：" : i == 5? "今日温度：" : "").append(weather[i]).append("\n");
                        }
                        Platform.runLater(()-> stage2_9.setText(str.toString()));
                    }catch (Exception e){
                        Platform.runLater(()-> stage2_9.setText(e.toString()));
                    }
                }).start();


                StringBuilder coords = new StringBuilder();
                for (String[] item: router){
                    coords.append(CoordinateTransformation.GPGGALatitude2GPS(Double.parseDouble(item[2])));
                    coords.append(",");
                    coords.append(CoordinateTransformation.GPGGALatitude2GPS(Double.parseDouble(item[1])));
                    if (!item[0].equals(router[router.length -1][0])){
                        coords.append(";");
                    }
                }
                JSONArray jsonArray = BMapChangePosition.changeGPSCoords(coords.toString());
                JavaUseJS.Run(stage2_webView, "addRouterAllPointBMap(" + jsonArray + ")");
//                String[][] finalRouter = router;
//                new Thread(new Runnable() {
//                    @Override
//                    public void run() {
//                        for (String[] i : finalRouter){
//                            try {
//                                Thread.sleep(120);
//                            } catch (InterruptedException e) {
//                                e.printStackTrace();
//                            }
//                            Platform.runLater(new Runnable() {
//                                @Override
//                                public void run() {
//                                    JavaUseJS.Run(stage2_webView, "addRouter(" + CoordinateTransformation.GPGGALatitude2GPS(Double.parseDouble(i[1])) + ", " + CoordinateTransformation.GPGGALatitude2GPS(Double.parseDouble(i[2])) + ")");
//                                }
//                            });
//                        }
//                    }
//                }).start();
            }
        });

    }
    @FXML
    public void close(ActionEvent actionEvent) {
        Stage stage = (Stage) stage2_back.getScene().getWindow();
        stage.close();
    }

    public void confirm(ActionEvent actionEvent) throws InterruptedException {
        Stage stage = (Stage) stage2_confirm.getScene().getWindow();
        ProgressStage.of(
                stage,
                new Task<Object>() {
                    @Override
                    protected Object call() throws Exception {
                        switch (currentSelectRouter){
                            case 0:
                                for (String[] i : Router.router1){
                                    sendRouter(i);
                                }
                                sendDBBBB();
                                break;
                            case 1:
                                for (String[] i : Router.router2){
                                    sendRouter(i);
                                }
                                sendDBBBB();
                                break;
                            case 2:
                                for (String[] i : Router.router3){
                                    sendRouter(i);
                                }
                                sendDBBBB();
                                break;
                            case 3:
                                for (String[] i : Router.router4){
                                    sendRouter(i);
                                }
                                sendDBBBB();
                                break;
                        }
                        Platform.runLater(new Runnable() {
                            @Override
                            public void run() {
                                stage.close();
                            }
                        });
                        return null;
                    }
                },
                "正在设置路线..."
        ).show();
//        System.out.println(currentSelectRouter);
    }

    private void sendRouter(String[] i) throws InterruptedException {
        SendRouter.setNum((byte) Integer.parseInt(i[0]));
        SendRouter.setLat(i[1]);
        SendRouter.setLong(i[2]);
        SendRouter.setDir((byte) Integer.parseInt(i[3]));
        new Thread(new Runnable(){
            @Override
            public void run() {
                Main.tcpHelper.sendHexMessage(SendRouter.getOrder());
            }
        }).start();
        Thread.sleep(1000);
    }
    private void sendDBBBB() throws InterruptedException {
        Thread.sleep(1000);
        Order_AutoControl.setFunction((byte) 10);   // 读取遍历校园
        new Thread(new Runnable(){
            @Override
            public void run() {
                Main.tcpHelper.sendHexMessage(Order_AutoControl.getOrder());
            }
        }).start();
    }
}
